package com.huluobo.kotlinim2006a.contract.login

import com.huluobo.kotlinim2006a.adapter.EMCallBackAdapter
import com.huluobo.kotlinim2006a.extention.isValidPassword
import com.huluobo.kotlinim2006a.extention.isValidUserName
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient

/**
 * Created by lc on 2023/2/2.
 */
class LoginPresenter(val view: LoginContract.View) : LoginContract.Presenter {
    override fun login(userName: String, password: String) {
        //1.验证用户名是否合法
        if (userName.isValidUserName()) {
            //2.验证密码是否合法
            if (password.isValidPassword()) {
                //3.触发登录的进度条
                view.onStartLogin()
                //4.发起网络请求登录到环信(成功和失败的回调)
                loginEaseMob(userName, password)
            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    //此方法相当于M层
    private fun loginEaseMob(userName: String, password: String) {
        EMClient.getInstance().login(userName, password, object : EMCallBackAdapter() {
            override fun onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups()//如果登录成功获取所有的群
                EMClient.getInstance().chatManager().loadAllConversations()//获取所有的会话列表
                runOnUIThread {
                    view.onLoggedInSuccess()
                }
            }

            override fun onError(code: Int, error: String?) {
                runOnUIThread {
                    view.onLoggedInFailed(error)
                }
            }
        })
    }
}